<template>
  <custom-dialog
    ref="dialog"
    :title="modalTitle" height="400px"
    :before-confirm="beforeConfirm" :on-confirm="onConfirm"
  >
    <el-form ref="form" :model="info" :rules="rules" label-width="120px">
      <el-form-item label="应用名称" prop="applicationName">
        <el-input v-model="info.applicationName"></el-input>
      </el-form-item>
      <el-form-item label="应用图标">
        <select-icon :value="info.applicationIcon" @selected="info.applicationIcon = $event">
          <template #default="{ selectedIcon }">
            <span v-if="selectedIcon">
              <svg-icon :name="selectedIcon" class="selected-icon"></svg-icon>
              {{ selectedIcon }}
              <svg-icon name="close" @click.stop="info.applicationIcon = ''"></svg-icon>
            </span>
            <el-button type="primary" v-else>选择图标</el-button>
          </template>
        </select-icon>
      </el-form-item>
      <el-form-item label="应用描述">
        <el-input
          type="textarea" v-model="info.remarks"
          :autosize="{minRows: 3, maxRows: 6}"
        ></el-input>
      </el-form-item>
    </el-form>
  </custom-dialog>
</template>

<script>
import CustomDialog from '@/components/custom-dialog'
import SelectIcon from '@/components/select-icon'
import { saveOrUpdateApplication } from '@/api/sysApplication'

const api = { saveOrUpdateApplication }
export default {
  name: 'operate-modal',
  components: { SelectIcon, CustomDialog },
  props: {
    modalTitle: String,
    data: {
      type: Object,
      default () {
        return {}
      }
    }
  },
  data () {
    return {
      info: {
        id: '',
        applicationName: '',
        applicationIcon: '',
        remarks: ''
      },
      rules: {
        applicationName: [
          { required: true, message: '请输入应用名称' }
        ]
      }
    }
  },
  methods: {
    open () {
      const isAdd = Object.keys(this.data).length === 0
      this.info = isAdd
        ? this.$options.data().info
        : {
            ...this.$options.data().info,
            ...this.data
          }
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
      this.$nextTick(() => {
        this.$refs.dialog.open()
      })
    },
    beforeConfirm () {
      return this.$refs.form.validate()
    },
    onConfirm (close) {
      const params = { ...this.info }
      if (params.id === '') {
        delete params.id
      }
      return api.saveOrUpdateApplication(params).then((res) => {
        if (res.code === 200) {
          this.$emit('save-success')
          this.$message.success('保存成功')
          close()
        }
      })
    },
  }
}
</script>

<style scoped>

</style>
